/**
 *    @file       threadgroup.h
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       02/11/2014 06:24:47 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com 
 */
#ifndef _SF_THREADGROUP_H_
#define _SF_THREADGROUP_H_
#include <vector>
#include "srvdef.h"
#include "message.h"
#include "threadmutex.h"
#include "workthread.h"

class threadgroup
{
public:
	threadgroup(bf_uint32_t type, bf_uint32_t size, const comargs *args);
	virtual ~threadgroup();

public:
	virtual bf_int_t init();
	virtual bf_int_t stop_all_thread();
	inline bf_int_t put_msg(message *msg)
	{
		if (!msg) return BF_ERROR;

		msghead &head = msg->get_msghead();
		if (head.m_thd_type != m_thd_type)
		{
			delete msg;
			return BF_ERROR;
		}
		
		if (head.m_thd_index == RAND_THD_INDEX)
		{
			bf_uint32_t cur_index = 0;
			m_index_lock.lock();
			cur_index = m_cur_index ++;
			if (m_cur_index >= m_grp_size) m_cur_index -= m_grp_size;
			m_index_lock.unlock();
			m_thread[cur_index]->put_msg(msg);
			return BF_OK;
		}
		else if (head.m_thd_index < m_grp_size)
		{
			m_thread[head.m_thd_index]->put_msg(msg);
		}
		return BF_ERROR;
	}

public:
	inline bf_uint32_t get_thd_type() {return m_thd_type;}

	inline bf_uint32_t get_grp_size() {return m_grp_size;}

	inline std::vector<workthread*> & get_thread() {return m_thread;}

protected:
	virtual void clear();

protected:
	bf_uint32_t m_thd_type;
	bf_uint32_t m_grp_size;
	bf_uint32_t m_cur_index;
	threadmutex m_index_lock;
	comargs *m_args;
	std::vector<workthread*> m_thread;
};

#endif

